import { StompClient } from '@/message/stomp';

const getDefaultState = () => ({
	client: null,
	subscriptions: {}
});

const state = getDefaultState();

const mutations = {
	RESET_STATE: state => {
		Object.assign(state, getDefaultState());
	},
	SET_CLIENT: (state, client) => {
		state.client = client;
	},
	ADD_SUBSCRIPTION: (state, { destination, subscription }) => {
		state.subscriptions = {
			...state.subscriptions,
			[destination]: subscription
		};
	},
	DEL_SUBSCRIPTION: (state, destination) => {
		const subscriptions = {
			...state.subscriptions
		};
		delete subscriptions[destination];
		state.subscriptions = subscriptions;
	}
};

const actions = {
	connect({ commit }, headers) {
		const client = new StompClient('/api/ws/stomp');
		commit('SET_CLIENT', client);
		return client.connect(headers);
	},
	disconnect({ commit, state }, headers) {
		const client = state.client;
		commit('RESET_STATE');
		return client.disconnect(headers);
	},
	addSubscription({ commit }, payload) {
		commit('ADD_SUBSCRIPTION', payload);
	},
	delSubscription({ commit }, destination) {
		commit('DEL_SUBSCRIPTION', destination);
	}
};

export default {
	namespaced: true,
	state,
	mutations,
	actions
};
